<?php

namespace App\Http\Controllers\front;

use App\Model\Cards;
use App\Model\Setting;
use App\Model\UserBill;
use App\Model\UserInterested;
use App\Model\UserPopularity;
use App\Model\UserTemplate;
use App\Model\UserTemplateClone;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Swagger\Annotations as SWG;

class PageTemplateController extends Controller
{
    /**
     * @SWG\Get(
     *     path="/front/personal_page/templates",
     *     tags={"个人网页"},
     *     summary="系统模板列表",
     *     description="系统模板列表",
     *     produces={"application/json"},
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="default", type="integer", description="默认模板"),
     *              @SWG\Property(
     *                  property="list",
     *                  description="列表",
     *                  type="array",
     *                  @SWG\Items(
     *                      @SWG\Property(property="id", type="integer", description="id"),
     *                      @SWG\Property(property="name", type="string", description="模板名称"),
     *                      @SWG\Property(property="cover", type="string", description="封面"),
     *                      @SWG\Property(property="sort", type="integer", description="排序"),
     *                      @SWG\Property(property="type", type="integer", description="类型"),
     *                      @SWG\Property(property="describe", type="string", description="描述"),
     *                      @SWG\Property(property="is_enabled", type="integer", description="是否可用"),
     *                      @SWG\Property(property="content", type="string", description="模板内容"),
     *                      @SWG\Property(property="path", type="string", description="路径"),
     *                      @SWG\Property(property="cate", type="string", description="分类"),
     *                      @SWG\Property(property="clazz", type="string", description="类样式"),
     *                      @SWG\Property(property="created_at", type="string", format="date", description="创建时间"),
     *                  )
     *              )
     *          )
     *      )
     * )
     */
    public function index()
    {
        $cate_id = \request('cate_id');
        if (empty($cate_id)){
            $templates = DB::table('personal_page_template')->where('is_enabled', 1)->paginate(\request('limit', 10));
        }else {
            $templates = DB::table('personal_page_template')->where('is_enabled', 1)->where('cate', $cate_id)->paginate(\request('limit', 10));
        }
        $default = DB::table('personal_page_template_user')->where('user_id', Auth::id())->orderByDesc('created_at')->first();
        //查询当前用户使用中的模板，未使用为0
        return $this->renderJson(['default' => $default ? $default->template_id : 0, 'list' => $templates]);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/user_temp",
     *     tags={"个人网页"},
     *     summary="用户拥有的固定模板",
     *     description="用户拥有的固定模板",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="id"),
     *                  @SWG\Property(property="template_id", type="string", description="模板id"),
     *              )
     *          )
     *      )
     * )
     */
    public function user_temp()
    {
        //根据用户查询
        $tmp = DB::table('personal_page_template_user')->select('id', 'template_id')->where('type',1)->where('user_id', Auth::id())->orderBy('created_at')->get();
        return $this->renderJson($tmp);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/temp_content/{id}",
     *     tags={"个人网页"},
     *     summary="系统模板内容",
     *     description="系统模板内容",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", type="integer", description="模板id"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="id", type="integer", description="id"),
     *              @SWG\Property(property="name", type="string", description="模板名称"),
     *              @SWG\Property(property="cover", type="string", description="封面"),
     *              @SWG\Property(property="sort", type="integer", description="排序"),
     *              @SWG\Property(property="type", type="integer", description="类型"),
     *              @SWG\Property(property="describe", type="string", description="描述"),
     *              @SWG\Property(property="is_enabled", type="integer", description="是否可用"),
     *              @SWG\Property(property="content", type="string", description="模板内容"),
     *              @SWG\Property(property="path", type="string", description="路径"),
     *              @SWG\Property(property="cate", type="string", description="分类"),
     *              @SWG\Property(property="clazz", type="string", description="类样式"),
     *              @SWG\Property(property="created_at", type="string", format="date", description="创建时间"),
     *          )
     *      )
     * )
     */
    public function temp_content($id)
    {
        $tmp = DB::table('personal_page_template')->where('id', $id)->first();
        return $this->renderJson($tmp);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/user_temp/{id}",
     *     tags={"个人网页"},
     *     summary="用户模板内容",
     *     description="用户模板内容",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", type="integer", description="用户模板id"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="id", type="integer", description="id"),
     *              @SWG\Property(property="user_id", type="integer", description="userid"),
     *              @SWG\Property(property="template_id", type="integer", description="系统模板id"),
     *              @SWG\Property(property="cover", type="string", description="封面"),
     *              @SWG\Property(property="title", type="string", description="名称"),
     *              @SWG\Property(property="content", type="string", description="内容"),
     *              @SWG\Property(property="is_default", type="integer", description="是否默认"),
     *              @SWG\Property(property="created_at", type="string", format="date", description="创建时间"),
     *              @SWG\Property(property="popularity", type="integer", description="人气"),
     *              @SWG\Property(property="cate", type="integer", description="分类"),
     *              @SWG\Property(property="components", type="string", description="使用到的组件"),
     *              @SWG\Property(property="type", type="integer", description="1固定模板2自定义模板"),
     *              @SWG\Property(property="background", type="string", description="背景"),
     *              @SWG\Property(property="is_clone", type="integer", description="是否允许克隆"),
     *              @SWG\Property(property="clone_price", type="integer", description="克隆售价"),
     *              @SWG\Property(property="motto", type="string", description="格言"),
     *          )
     *      )
     * )
     */
    public function user_temp_content($id)
    {
        $tmp = DB::table('personal_page_template_user')->where('id', $id)->first();

        $popularity = DB::table('personal_page_template_user')->where('user_id', $tmp->user_id)->sum('popularity');
        $card = Cards::where('user_id', $tmp->user_id)->first();
        $tmp->motto = $card?$card->motto:'';
        $tmp->popularity = $popularity;
        return $this->renderJson($tmp);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/user_temp/bycate",
     *     tags={"个人网页"},
     *     summary="获取同一分类下用户其他固定模板",
     *     description="获取同一分类下用户其他固定模板",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="temp_id", in="query", type="integer", description="当前模板的系统id"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="id", type="integer", description="id"),
     *              @SWG\Property(property="user_id", type="integer", description="userid"),
     *              @SWG\Property(property="template_id", type="integer", description="系统模板id"),
     *              @SWG\Property(property="cover", type="string", description="封面"),
     *              @SWG\Property(property="title", type="string", description="名称"),
     *              @SWG\Property(property="content", type="string", description="内容"),
     *              @SWG\Property(property="is_default", type="integer", description="是否默认"),
     *              @SWG\Property(property="created_at", type="string", format="date", description="创建时间"),
     *              @SWG\Property(property="popularity", type="integer", description="人气"),
     *              @SWG\Property(property="cate", type="integer", description="分类"),
     *              @SWG\Property(property="components", type="string", description="使用到的组件"),
     *              @SWG\Property(property="type", type="integer", description="1固定模板2自定义模板"),
     *              @SWG\Property(property="background", type="string", description="背景"),
     *              @SWG\Property(property="is_clone", type="integer", description="是否允许克隆"),
     *              @SWG\Property(property="clone_price", type="integer", description="克隆售价"),
     *          )
     *      )
     * )
     */
    public function defaultByCate(Request $request)
    {
        $temp_id = $request->input('temp_id');
        $temp = DB::table('personal_page_template')->find($temp_id);
        if (empty($temp)){
            throw new ModelNotFoundException();
        }
        $user_temp = DB::table('personal_page_template_user')->where('type', 1)->where('cate', $temp->cate)->where('user_id', Auth::id())->orderByDesc('created_at')->first();
        return $this->renderJson($user_temp);
    }

    /**
     * @SWG\Post(
     *     path="/front/personal_page/user_temp",
     *     tags={"个人网页"},
     *     summary="用户添加个人网页",
     *     description="用户添加个人网页",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="template_id", in="formData", required=true, type="integer", description="系统模板id"),
     *     @SWG\Parameter(name="content", in="formData", required=true, type="string", description="内容"),
     *     @SWG\Parameter(name="title", in="formData", type="string", description="标题"),
     *     @SWG\Response(
     *          response="200",
     *          description="操作成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="id", type="integer", description="id")
     *          )
     *      )
     * )
     */
    public function add_user_temp(Request $request)
    {
        $this->validate($request, [
            'template_id' => 'required',
            'content' => 'required'
        ]);
        $template_id = $request->input('template_id');
        $temp = DB::table('personal_page_template')->find($template_id);
        if (empty($temp)){
            return $this->fail('模板不存在');
        }
        //删除用户当前模板其他信息
        $count = UserTemplate::where('user_id', Auth::id())->where('type', 1)->where('template_id',$template_id)->count();
        if ($count == 0){
            $id = DB::table('personal_page_template_user')->insertGetId(['type' => 1,'is_default' => 0, 'user_id' => Auth::id(), 'template_id' => $request->input('template_id'),'title'=>$request->input('title')?:'', 'content' => $request->input('content'), 'cate' => $temp->cate, 'created_at' => Carbon::now()]);
        }else {
            $userPage = UserTemplate::where('user_id', Auth::id())->where('type', 1)->where('template_id', $template_id)->orderByDesc('created_at')->first();
            if ($count > 1){
                try {
                    UserTemplate::where('user_id', Auth::id())->where('type', 1)->where('template_id', $template_id)->where('created_at', '<', $userPage->created_at)->delete();
                } catch (\Exception $e) {
                }
            }
            $userPage->content = $request->input('content');
            $userPage->title = $request->input('title')?:'';
            $userPage->created_at = Carbon::now();
            $userPage->save();
            $id = $userPage->id;
        }


        //统计网页
        $total = UserTemplate::where('user_id', Auth::id())->count();
        if ($total <= 1){
            //刚刚添加的一条
            //设置为默认
            $this->setDefault($id);
        }else{
            //是否有设置默认
            $default = UserTemplate::where('user_id', Auth::id())->where('is_default', 1)->first();
            if (empty($default)){
                //没有设置默认设置当前为默认
                $this->setDefault($id);
            }
        }
        return $this->renderJson(['id' => $id]);
    }

    /**
     * @SWG\Put(
     *     path="/front/personal_page/user_temp/{id}",
     *     tags={"个人网页"},
     *     summary="用户添加个人网页",
     *     description="用户添加个人网页",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="template_id", in="path", required=true, type="integer", description="需要修改的id"),
     *     @SWG\Parameter(name="template_id", in="formData", required=true, type="integer", description="系统模板id"),
     *     @SWG\Parameter(name="content", in="formData", required=true, type="string", description="内容"),
     *     @SWG\Parameter(name="title", in="formData", type="string", description="标题"),
     *     @SWG\Response(
     *          response="200",
     *          description="操作成功",
     *      )
     * )
     */
    public function eit_user_temp(Request $request, $id)
    {
        $this->validate($request, [
            'template_id' => 'required',
            'content' => 'required'
        ]);
        DB::table('personal_page_template_user')->where('id', $id)->update(['content' => $request->input('content')]);
        //如果设置了默认
//        if ($request->has('is_default') && $request->input('is_default') == 1){
//            $this->setDefault($id);
//        }
        return $this->success();
    }

    /**
     * 设置默认用户模板
     * @param $id
     * @return bool
     */
    private function setDefault($id)
    {
        try {
            DB::transaction(function () use ($id) {
                //清除当前用户默认状态
                DB::table('personal_page_template_user')->where('user_id', Auth::id())->where('is_default', 1)->update(['is_default' => 0]);
                //设置默认
                DB::table('personal_page_template_user')->where('id', $id)->update(['is_default' => 1]);
            });
            return true;
        } catch (\Throwable $e) {
            return false;
        }
    }

    /**
     * @SWG\Post(
     *     path="/front/personal_page/user_default_temp/{id}",
     *     tags={"个人网页"},
     *     summary="设置某个用户模板为默认",
     *     description="设置某个用户模板为默认",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="template_id", in="path", required=true, type="integer", description="需要设置为默认的id"),
     *     @SWG\Response(
     *          response="200",
     *          description="操作成功",
     *      )
     * )
     */
    public function user_temp_default($id)
    {
        if ($this->setDefault($id)) {
            return $this->success();
        }
        return $this->error();
    }

    /**
     * @SWG\Delete(
     *     path="/front/personal_page/user_temp/{id}",
     *     tags={"个人网页"},
     *     summary="删除个人网页",
     *     description="删除个人网页",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", required=true, type="string", description="id"),
     *     @SWG\Response(
     *          response="200",
     *          description="操作成功"
     *      )
     * )
     */
    public function del_user_temp($id)
    {
        $r = UserTemplate::findOrFail($id);
        if ($r->is_default == 1){
            return $this->fail('设置为默认不能删除');
        }
        if ($r) {
            $r->delete();
            return $this->success();
        }
        return $this->error();
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/get_user_temp",
     *     tags={"个人网页"},
     *     summary="根据用户模板id获取用户模板",
     *     description="根据用户模板id获取用户模板(不需要登录获取个人网页)",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="temp_id", in="path", type="integer", description="用户模板id"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="id", type="integer", description="id"),
     *              @SWG\Property(property="user_id", type="integer", description="userid"),
     *              @SWG\Property(property="template_id", type="integer", description="系统模板id"),
     *              @SWG\Property(property="cover", type="string", description="封面"),
     *              @SWG\Property(property="title", type="string", description="名称"),
     *              @SWG\Property(property="content", type="string", description="内容"),
     *              @SWG\Property(property="is_default", type="integer", description="是否默认"),
     *              @SWG\Property(property="created_at", type="string", format="date", description="创建时间"),
     *              @SWG\Property(property="popularity", type="integer", description="人气"),
     *              @SWG\Property(property="cate", type="integer", description="分类"),
     *              @SWG\Property(property="components", type="string", description="使用到的组件"),
     *              @SWG\Property(property="type", type="integer", description="1固定模板2自定义模板"),
     *              @SWG\Property(property="background", type="string", description="背景"),
     *              @SWG\Property(property="is_clone", type="integer", description="是否允许克隆"),
     *              @SWG\Property(property="clone_price", type="integer", description="克隆售价"),
     *              @SWG\Property(property="motto", type="string", description="格言"),
     *              @SWG\Property(property="has_card", type="boolean", description="是否有名片信息"),
     *          )
     *      )
     * )
     */
    public function get_user_temp()
    {
        $this->validate(\request(), [
            'temp_id' => 'required'
        ], [
            'temp_id.required' => '用户模板id不能为空'
        ]);
        $temp_id = \request('temp_id');
        $tmp = DB::table('personal_page_template_user')->where('id', $temp_id)->first();
        if (empty($tmp)) {
            throw new ModelNotFoundException();
        }
        $tmp->has_card = false;
        $tmp->motto = '';
        $card = Cards::where('user_id', $tmp->user_id)->first();
        if ($card) {
            $tmp->has_card = true;
            $tmp->motto = $card->motto;
        }
        $this->popularity($tmp->id, $tmp->user_id);
        //$popularity = DB::table('personal_page_template_user')->where('user_id', $tmp->user_id)->sum('popularity');
        $tmp->popularity = UserTemplate::popularity($tmp->user_id);
        return $this->renderJson($tmp);
    }

    private function popularity($temp_id, $temp_user_id){
        //增加人气
        $pop = true;
        if (Auth::id() == $temp_user_id) {
            $pop = false;
        }
        //人气是否可以增长
        if ($pop) {
            //如果已登录判断是否是自己访问
            DB::table('personal_page_template_user')->where('id', $temp_id)->increment('popularity');

            //记录日志
            //已登录状态 记录具体访问人
            $popularityM = DB::table('personal_page_template_popularity');
            if (Auth::check()) {
                $p = $popularityM->where('target', $temp_id)->where('type', 1)->where('user_id', Auth::id())->orderByDesc('created_at')->first();
                if (empty($p)) {
                    //没有当前访问者的记录，直接写入信息
                    $popularityM->insert(['target' => $temp_id, 'target_user_id' => $temp_user_id, 'type' => 1, 'user_id' => Auth::id(), 'ip' => \request()->getClientIp(), 'created_at' => Carbon::now()]);
                } else {
                    //判断上次访问是否是当天
                    if (!Carbon::parse($p->created_at)->isToday()) {
                        //不是当天写入记录
                        $popularityM->insert(['target' => $temp_id, 'target_user_id' => $temp_user_id, 'type' => 1, 'user_id' => Auth::id(), 'ip' => \request()->getClientIp(), 'created_at' => Carbon::now()]);
                    }
                }
            } else {
                //未登录状态，写入游客记录
                $p = $popularityM->where('target', $temp_id)->where('type', 0)->where('ip', \request()->getClientIp())->orderByDesc('created_at')->first();
                if (empty($p)) {
                    //没有该ip访问记录
                    $popularityM->insert(['target' => $temp_id, 'target_user_id' => $temp_user_id, 'type' => 0, 'ip' => \request()->getClientIp(), 'created_at' => Carbon::now()]);
                } else {
                    //上次该ip访问时间
                    if (!Carbon::parse($p->created_at)->isToday()) {
                        $popularityM->insert(['target' => $temp_id, 'target_user_id' => $temp_user_id, 'type' => 0, 'ip' => \request()->getClientIp(), 'created_at' => Carbon::now()]);
                    }
                }
            }
        }
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/categories",
     *     tags={"个人网页"},
     *     summary="固定模板分类列表",
     *     description="固定模板分类列表",
     *     produces={"application/json"},
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="id"),
     *                  @SWG\Property(property="title", type="string", description="分类名"),
     *                  @SWG\Property(property="is_enabled", type="integer", description="是否启用"),
     *              )
     *          )
     *      )
     * )
     */
    public function categories()
    {
        $res = DB::table("personal_page_template_category")->get();
        return $this->renderJson($res);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/default_template",
     *     tags={"个人网页"},
     *     summary="根据用户获取默认模板id",
     *     description="根据用户获取默认模板id",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="user_id", in="query", type="integer", required=true, description="用户id"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="id", type="integer", description="模板id")
     *          )
     *      )
     * )
     */
    public function default_temp()
    {
        $this->validate(\request(), [
            'user_id' => 'required'
        ]);
        $user_id = request('user_id');
        $tmp = DB::table('personal_page_template_user')->where('is_default', 1)->where('user_id', $user_id)->first();
        if (empty($emp)){
            $tmp = UserTemplate::where('user_id', $user_id)->orderByDesc('created_at')->first();
        }
        return $this->renderJson(['id' => $tmp ? $tmp->id : false]);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/user_temp/record",
     *     tags={"个人网页"},
     *     summary="个人网页浏览记录",
     *     description="个人网页浏览记录",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="page_id", type="integer", description="个人网页id"),
     *                  @SWG\Property(property="user_id", type="integer", description="用户"),
     *                  @SWG\Property(property="type", type="integer", description="游客或用户"),
     *                  @SWG\Property(property="name", type="string", description="用户名"),
     *                  @SWG\Property(property="portrait", type="string", description="头像"),
     *                  @SWG\Property(property="page_type", type="integer", description="1固定2自定义"),
     *                  @SWG\Property(property="company", type="integer", description="公司"),
     *                  @SWG\Property(property="created_at", type="string", format="date", description="时间"),
     *              )
     *          )
     *      )
     * )
     */
    public function record()
    {
        $row = DB::table('personal_page_template_popularity as p')
            ->select('pu.id as page_id','p.user_id','p.type', 'p.created_at', 'c.user_name', 'c.head_picture','u.wechat_name', 'u.head_portrait', 'pu.type as page_type', 'c.company')
            ->leftJoin('cards as c', 'c.user_id', '=', 'p.user_id')
            ->leftJoin('user_detail as u', 'u.user_id', '=', 'p.user_id')
            ->leftJoin('personal_page_template_user as pu', 'pu.id', '=', DB::raw('(SELECT MAX(id) from personal_page_template_user where user_id=p.user_id)'))
            ->where('target_user_id', Auth::id())
            ->orderByDesc('created_at')
            ->paginate(\request('limit', 10));
        $data = $row->toArray();
        $items = collect($data['data']);
        $items = $items->map(function ($item) {
            $item = collect($item)->toArray();
            $item['name'] = $item['user_name']?:$item['wechat_name'];
            $item['portrait'] = $item['head_picture']?:$item['head_portrait'];
            unset($item['user_name']);
            unset($item['wechat_name']);
            unset($item['head_picture']);
            unset($item['head_portrait']);
            return $item;
        });
        //根据日期分组
//        $items = $items->groupBy(function ($item){
//            $item = collect($item)->toArray();
//            return Carbon::parse($item['created_at'])->toDateString();
//        });
        $data['data'] = $items;
        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/customs/categories",
     *     tags={"个人网页"},
     *     summary="自定义模板分类列表",
     *     description="自定义模板分类列表",
     *     produces={"application/json"},
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="id"),
     *                  @SWG\Property(property="name", type="string", description="分类名"),
     *                  @SWG\Property(property="cover", type="string", description="封面"),
     *                  @SWG\Property(property="class_name", type="string", description="类名"),
     *                  @SWG\Property(property="type", type="string", description=""),
     *              )
     *          )
     *      )
     * )
     */
    public function custom_category()
    {
        $g = DB::table('personal_page_custom_categories')->where('is_enabled', 1)->orderByDesc('sort')->get();
        return $this->renderJson($g);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/customs/components",
     *     tags={"个人网页"},
     *     summary="自定义模板组件",
     *     description="自定义模板组件",
     *     produces={"application/json"},
     *     @SWG\Parameter(name="cate_id", in="query", type="integer", description="分类id"),
     *     @SWG\Parameter(name="ratio", in="query", type="string", description="ratio"),
     *     @SWG\Parameter(name="type", in="query", type="string", description="类型"),
     *     @SWG\Parameter(name="is_slide", in="query", type="string", description="是否轮播"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="id"),
     *                  @SWG\Property(property="cate", type="integer", description="分类"),
     *                  @SWG\Property(property="name", type="string", description="名称"),
     *                  @SWG\Property(property="cover", type="string", description="封面"),
     *                  @SWG\Property(property="describe", type="string", description="描述"),
     *                  @SWG\Property(property="content", type="string", description="内容"),
     *                  @SWG\Property(property="has_vip", type="integer", description="是否是vip能用"),
     *                  @SWG\Property(property="price", type="integer", description="价格"),
     *                  @SWG\Property(property="type", type="integer", description="类型"),
     *                  @SWG\Property(property="ratio", type="integer", description="ratio"),
     *                  @SWG\Property(property="is_slide", type="integer", description="slide"),
     *              )
     *          )
     *      )
     * )
     */
    public function custom_components(Request $request)
    {
        $component = DB::table('personal_page_custom_component');
        if ($request->has('cate_id')){
            $component->where('cate', $request->input('cate_id'));
        }
        if ($request->has('ratio')){
            $component->where('ratio', $request->input('ratio'));
        }
        if ($request->has('type')){
            $component->where('type', $request->input('type'));
        }
        if ($request->has('is_slide')){
            $component->where('is_slide', $request->input('is_slide'));
        }
        $component->where('is_enabled', 1);
        $components = $component->get();
        return $this->renderJson($components);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/customs/components/{id}",
     *     tags={"个人网页"},
     *     summary="自定义模板组件详情",
     *     description="自定义模板组件详情",
     *     produces={"application/json"},
     *     @SWG\Parameter(name="cate_id", in="path", type="integer", description="组件id"),
     *     @SWG\Response(
     *          response="200",
     *          description="成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="id", type="integer", description="id"),
     *              @SWG\Property(property="cate", type="integer", description="分类"),
     *              @SWG\Property(property="name", type="string", description="名称"),
     *              @SWG\Property(property="cover", type="string", description="封面"),
     *              @SWG\Property(property="describe", type="string", description="描述"),
     *              @SWG\Property(property="content", type="string", description="内容"),
     *              @SWG\Property(property="has_vip", type="integer", description="是否是vip能用"),
     *              @SWG\Property(property="price", type="integer", description="价格"),
     *              @SWG\Property(property="type", type="integer", description="类型"),
     *              @SWG\Property(property="ratio", type="integer", description="ratio"),
     *              @SWG\Property(property="is_slide", type="integer", description="slide"),
     *          )
     *      )
     * )
     */
    public function custom_component($id)
    {
        $c = DB::table('personal_page_custom_component')->find($id);
        if (!$c){
            throw new ModelNotFoundException();
        }
        return $this->renderJson($c);
    }

    /**
     * @SWG\Post(
     *     path="/front/personal_page/customs",
     *     tags={"个人网页"},
     *     summary="添加自定义网页",
     *     description="添加自定义网页",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="components", in="formData", required=true, type="string", description="组件列表"),
     *     @SWG\Parameter(name="title", in="formData", required=true, type="string", description="标题"),
     *     @SWG\Parameter(name="content", in="formData", required=true, type="string", description="内容"),
     *     @SWG\Parameter(name="clone_id", in="formData", type="string", description="克隆id"),
     *     @SWG\Parameter(name="background", in="formData", type="string", description="背景"),
     *     @SWG\Parameter(name="cover", in="formData", type="string", description="封面"),
     *     @SWG\Parameter(name="is_clone", in="formData", type="string", description="是否克隆"),
     *     @SWG\Parameter(name="clone_price", in="formData", type="string", description="克隆价格"),
     *     @SWG\Response(
     *          response="200",
     *          description="成功"
     *      )
     * )
     */
    public function add_custom(Request $request)
    {
        $this->validate($request, [
            'components' => 'required',
            'title' => 'required',
            'content' => 'required'
        ]);
        //组件
        $components = $request->input('components');
        $setting = Setting::getValue('person-page-custom');
        if ($setting['value'] == 1){
            //会员限制
            if (!User::is_vip(Auth::id())){
                //查询已有的自定义网页
                $count = UserTemplate::where('user_id', Auth::id())->where('type', 2)->count();
                if ($count >= 1) {
                    return $this->fail('非会员只能添加一个自定义网页');
                }
            }
        }
        try {
            DB::beginTransaction();

            if (!empty($request->input('clone_id'))){
                $clone = UserTemplateClone::where('id',\request('clone_id'))->where('user_id', Auth::id())->first();
                if (is_null($clone)){
                    DB::rollBack();
                    return $this->fail('数据不存在');
                }
                $clone_data = UserTemplate::find($clone->template_id);
                if ($clone_data->clone_price > 0 && $clone->is_paid == 0){
                    DB::rollBack();
                    return $this->fail('你还未支付');
                }
                $clone->is_cloned = 1;
                $clone->save();
            }
            $id = DB::table('personal_page_template_user')->insertGetId([
                'type' => 2,
                'user_id' => Auth::id(),
                'title' => $request->input('title'),
                'cover' => $request->input('cover'),
                'content' => $request->input('content'),
                'components' => implode(',' , $components),
                'background' => $request->input('background')?:'',
                'is_clone' => $request->input('is_clone'),
                'created_at' => Carbon::now()
            ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e);
            return $this->error($e);
        }
        //统计网页
        $total = UserTemplate::where('user_id', Auth::id())->count();
        if ($total <= 1){
            //刚刚添加的一条
            //设置为默认
            $this->setDefault($id);
        }else{
            //是否有设置默认
            $default = UserTemplate::where('user_id', Auth::id())->where('is_default', 1)->first();
            if (empty($default)){
                //没有设置默认设置当前为默认
                $this->setDefault($id);
            }
        }

        return $this->renderJson(['id' => $id]);
    }

    /**
     * @SWG\Put(
     *     path="/front/personal_page/customs/{id}",
     *     tags={"个人网页"},
     *     summary="修改自定义网页",
     *     description="修改自定义网页",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", type="integer", description="id"),
     *     @SWG\Parameter(name="components", in="formData", type="string", description="组件列表"),
     *     @SWG\Parameter(name="title", in="formData", type="string", description="标题"),
     *     @SWG\Parameter(name="background", in="formData", type="string", description="内容"),
     *     @SWG\Parameter(name="cover", in="formData", type="string", description="内容"),
     *     @SWG\Parameter(name="is_clone", in="formData", type="string", description="内容"),
     *     @SWG\Parameter(name="clone_price", in="formData", type="string", description="内容"),
     *     @SWG\Response(
     *          response="200",
     *          description="成功"
     *      )
     * )
     */
    public function edit_custom(Request $request, $id)
    {
        $t = UserTemplate::find($id);
        if (empty($t)){
            throw new ModelNotFoundException();
        }
        if ($t->user_id != Auth::id()){
            return $this->fail('你不是拥有者', 401);
        }
        if ($request->has('components')){
            $t->components = implode(',' , $request->input('components'));
        }
        if ($request->has('title')){
            $t->title = $request->input('title');
        }
        if ($request->has('content')){
            $t->content = $request->input('content');
        }
        if ($request->has('background')){
            $t->background = $request->input('background');
        }
        if ($request->has('cover')){
            $t->cover = $request->input('cover');
        }
        if ($request->has('is_clone')){
            $t->is_clone = $request->input('is_clone');
        }
        if ($request->has('clone_price')){
            $t->clone_price = $request->input('clone_price');
        }
        $t->save();
        return $this->success();
    }

    /**
     * @SWG\Delete(
     *     path="/front/personal_page/customs/{id}",
     *     tags={"个人网页"},
     *     summary="删除个人网页",
     *     description="删除个人网页",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", required=true, type="string", description="id"),
     *     @SWG\Response(
     *          response="200",
     *          description="删除成功"
     *      )
     * )
     */
    public function del_custom($id)
    {
        $t = UserTemplate::findOrFail($id);
        if ($t->is_default == 1){
            return $this->fail('默认不能删除');
        }
        $t->delete();
        return $this->success();
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/customs/",
     *     tags={"个人网页"},
     *     summary="自定义网页列表",
     *     description="自定义网页列表",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="id"),
     *                  @SWG\Property(property="title", type="string", description="标题"),
     *                  @SWG\Property(property="components", type="string", description="组件"),
     *                  @SWG\Property(property="content", type="string", description="内容"),
     *                  @SWG\Property(property="created_at", type="string", format="date", description="时间"),
     *              )
     *          )
     *      )
     * )
     */
    public function custom_list()
    {
        $list = DB::table('personal_page_template_user')->orderByDesc('created_at')->where('type', 2)->where('user_id',Auth::id())->select(['id', 'title', 'components', 'content', 'created_at'])->paginate(\request('limit', 10));
        $data = collect($list->toArray());
        $items = collect($data['data']);
        $items  = $items->map(function ($item){
            $item = collect($item)->toArray();
            $item['components'] = explode(',' , $item['components'])?:[];
            return $item;
        });
        $data['data'] = $items->toArray();
        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/customs/{id}",
     *     tags={"个人网页"},
     *     summary="根据id获取自定义网页",
     *     description="自定义网页",
     *     produces={"application/json"},
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="id", type="integer", description="id"),
     *              @SWG\Property(property="is_clone", type="integer", description="是否克隆"),
     *              @SWG\Property(property="clone_price", type="integer", description="克隆价格"),
     *              @SWG\Property(property="user_id", type="integer", description="用户id"),
     *              @SWG\Property(property="title", type="string", description="标题"),
     *              @SWG\Property(property="components", type="string", description="组件"),
     *              @SWG\Property(property="background", type="string", description="背景"),
     *              @SWG\Property(property="type", type="integer", description="类型"),
     *              @SWG\Property(property="has_card", type="boolean", description="是否有名片"),
     *              @SWG\Property(property="motto", type="string", description="格言"),
     *              @SWG\Property(property="share", type="integer", description="分享量"),
     *              @SWG\Property(property="created_at", type="string", format="date", description="时间"),
     *              @SWG\Property(
     *                  property="user",
     *                  type="object",
     *                  description="用户信息",
     *                  @SWG\Property(property="id", type="integer", description="用户id"),
     *                  @SWG\Property(property="name", type="string", description="名字"),
     *                  @SWG\Property(property="portrait", type="string", description="头像"),
     *              )
     *          )
     *      )
     * )
     */
    public function get_custom($id)
    {
        $c = DB::table('personal_page_template_user')->select(['id', 'is_clone', 'clone_price','user_id', 'title', 'components', 'background','content', 'created_at', 'type', 'share', 'popularity'])->find($id);
        if (empty($c)){
            throw new ModelNotFoundException();
        }
        $this->popularity($c->id, $c->user_id);
        $c->components = explode(',', $c->components);
        //$popularity = DB::table('personal_page_template_user')->where('user_id', $c->user_id)->sum('popularity');
//        $c->popularity = UserTemplate::popularity($c->user_id);
        $c->has_card = false;
        $c->motto = '';
        $card = Cards::where('user_id', $c->user_id)->first();
        if ($card) {
            $c->has_card = true;
            $c->motto = $card->motto;
        }
        $user = User::find($c->user_id);
        $c->user = [
            'id' => $c->user_id,
            'name' => $user->name(),
            'portrait' => $user->portrait()
        ];
		$c->interest = UserInterested::where('target_user_id',$c->user_id)->count();
		$c->is_interest = UserInterested::isInterested($c->user_id);//是否已经有感兴趣记录
		//人气记录
		UserPopularity::add(UserPopularity::MICRO_WEB,$c->user_id,$id);
        return $this->renderJson($c);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/all",
     *     tags={"个人网页"},
     *     summary="所有个人网页",
     *     description="所有个人网页",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="offset", in="query", type="integer", description="起始(前端分页)"),
     *     @SWG\Parameter(name="page", in="query", type="integer", description="第几页(后端分页)"),
     *     @SWG\Response(
     *          response="200",
     *          description="列表",
     *          @SWG\Schema(
     *              @SWG\Property(property="count", type="integer", description="总数(前端分页时有)"),
     *              @SWG\Property(
     *                  property="list",
     *                  description="前端分页时有这一级",
     *                  type="array",
     *                  @SWG\Items(
     *                      @SWG\Property(property="id", type="integer", description="文章id"),
     *                      @SWG\Property(property="cate", type="string", description="分类"),
     *                      @SWG\Property(property="title", type="string", description="标题"),
     *                      @SWG\Property(property="popularity", type="integer", description="浏览量"),
     *                      @SWG\Property(property="template_id", type="integer", description="浏览量"),
     *                      @SWG\Property(property="share", type="integer", description="浏览量"),
     *                      @SWG\Property(property="content", type="string", description="组件"),
     *                      @SWG\Property(property="components", type="string", description="内容"),
     *                      @SWG\Property(property="type", type="string", description="类型"),
     *                      @SWG\Property(property="created_at", type="string", format="date", description="发布时间"),
     *                  )
     *              )
     *          )
     *      )
     * )
     */
    public function all()
    {
        $userId = Auth::id();
        $m = UserTemplate::from('personal_page_template_user as u')
            ->select('u.id', 'u.is_default', 'c.title as cate', 'share', 'u.title', 'u.template_id', 'u.content', 'u.components', 'u.type', 'u.created_at', 'u.popularity', 'u.cover')
            ->where('u.user_id', $userId)
            ->where('u.type', 2)
            ->leftJoin('personal_page_template_category as c', 'c.id', '=', 'u.cate');
        $data = [];
        if (\request()->has('offset')) {
            $data['count'] = $m->count();
            $data['list'] = $m->offset(\request('offset'))->limit(\request('limit'))->get();
            foreach ($data['list'] as &$item) {
                $content = json_decode($item->content);
                foreach ($content as $value) {
                    if ($value->type == 'slider') {
                        $item->cover = $value->children[0]->img->src;
                    }
                }
            }
        }else{
            $data = $m->paginate(\request('limit', 10));
            foreach ($data as &$item) {
                $content = json_decode($item->content);
                foreach ($content as $value) {
                    if ($value->type == 'slider') {
                        $item->cover = $value->children[0]->img->src;
                    }
                }
            }
        }

//            ->get();
//
//        $list = UserTemplate::from('personal_page_template_user as u')
//            ->select('u.id', 'u.is_default', 'c.title as cate', 'u.title', 'u.template_id', 'u.content', 'u.components', 'u.type', 'u.created_at')
//            ->where('u.user_id', $userId)
//            ->where('u.type', 2)
//            ->leftJoin('personal_page_template_category as c', 'c.id', '=', 'u.cate')
//            ->get();
//        $r = $list->merge($list1);

        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/rank",
     *     tags={"个人网页"},
     *     summary="个人网页排行",
     *     description="个人网页排行",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="列表",
     *          @SWG\Schema(
     *              @SWG\Property(property="ranking", type="integer", description="自己的排名"),
     *              @SWG\Property(property="is_clone", type="integer", description="是否只显示允许被克隆的"),
     *              @SWG\Property(
     *                  property="rank",
     *                  type="array",
     *                  description="排名",
     *                  @SWG\Items(
     *                      @SWG\Property(property="id", type="integer", description="id"),
     *                      @SWG\Property(property="is_clone", type="integer", description="是否允许克隆"),
     *                      @SWG\Property(property="title", type="string", description="标题"),
     *                      @SWG\Property(property="clone_price", type="integer", description="克隆价格"),
     *                      @SWG\Property(property="content", type="string", description="内容"),
     *                      @SWG\Property(property="share_count", type="integer", description="分享量"),
     *                      @SWG\Property(property="popularity", type="integer", description="浏览量"),
     *                      @SWG\Property(property="type", type="integer", description="类型"),
     *                      @SWG\Property(property="cover", type="string", description="封面"),
     *                      @SWG\Property(
     *                          property="user",
     *                          type="object",
     *                          @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="name", type="string", description="姓名"),
     *                          @SWG\Property(property="portrait", type="string", description="头像"),
     *                      ),
     *                  )
     *              ),
     *              @SWG\Property(
     *                  property="meta",
     *                  type="object",
     *                  description="分页信息"
     *                  )
     *          )
     *      )
     * )
     */
    public function rank()
    {
        $paginate = UserTemplate::from('personal_page_template_user as p')
        ->select('p.*','c.user_name', 'c.head_picture','ud.wechat_name','ud.head_portrait')
            ->leftJoin('cards as c', 'c.user_id', '=', 'p.user_id')
            ->leftJoin('user_detail as ud', 'ud.user_id', '=', 'p.user_id')
            ->where('type', 2)->when(\request('is_clone'), function ($query, $value) {
                $query->where('p.is_clone', 1);
            })->orderByDesc('p.popularity')->orderByDesc('p.id')->paginate(\request('limit', 10));
        $ranks = $paginate->items();
        $paginate = $paginate->toArray();
        $rank = [];
        foreach ($ranks as $r) {
            $tmp = [
                'id' => $r->id,
                'is_clone' => $r->is_clone,
                'title' => $r->title,
                'clone_price' => $r->clone_price,
                'content' => $r->content,
                'share_count' => $r->share,
                'popularity' => $r->popularity,
                'type' => $r->type,
                'user' => [
                    'id' => $r->user_id,
                    'name' => $r->user_name?:$r->wechat_name?:'',
                    'portrait' => $r->head_picture?:$r->head_portrait?:''
                ]
            ];
            $tmp['cover'] = '';
            $content = json_decode($r->content);
            foreach ($content as $value) {
                if ($value->type == 'slider') {
                    $tmp['cover'] = $value->children[0]->img->src;
                }
            }
            $rank[] = $tmp;
        }
        $data = [
            'rank' => $rank,
            'ranking' => 0
        ];
        if (Auth::check() && UserTemplate::where('type', 2)->where('user_id', Auth::id())->first()){
            $sub = DB::table(DB::raw('personal_page_template_user a, (select (@rowno:=0)) b'))->select(DB::raw('a.user_id, a.popularity,(@rowno:=@rowno+1) as rowno'))
                ->where('a.type', 2)->when(\request('is_clone'), function ($query) {
                    $query->where('a.is_clone', 1);
                })->orderByDesc('a.popularity')->orderByDesc('a.id');
            $rowno = DB::table(DB::raw("({$sub->toSql()}) as c"))->mergeBindings($sub)->where('c.user_id', Auth::id())->orderByDesc('c.popularity')->value('c.rowno');
            $data['ranking'] = $rowno;
        }
        unset($paginate['data']);
        $data['meta'] = $paginate;
        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/customs/background",
     *     tags={"个人网页"},
     *     summary="自定义背景列表",
     *     description="自定义背景列表",
     *     produces={"application/json"},
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="id", type="integer", description="id"),
     *              @SWG\Property(property="name", type="string", description="名称"),
     *              @SWG\Property(property="describe", type="string", description="描述"),
     *              @SWG\Property(property="url", type="string", description="url"),
     *          )
     *      )
     * )
     */
    public function custom_background()
    {
        $background = DB::table('personal_page_custom_background')->where('is_enabled', 1)->get();
        return $this->renderJson($background);
    }

    /**
     * @SWG\Post(
     *     path="/front/personal_page/custom/clone",
     *     tags={"个人网页"},
     *     summary="克隆订单",
     *     description="克隆订单",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="temp_id", in="formData", type="integer", description="被克隆的模板id"),
     *     @SWG\Response(
     *          response="200",
     *          description="成功",
     *          @SWG\Schema(
     *              @SWG\Property(property="clone_id", type="integer", description="克隆订单id")
     *          )
     *      )
     * )
     */
    public function clone_custom()
    {
//        if (!\request('ignore')) {
//            $clone = UserTemplateClone::where('user_id', Auth::id())->where('is_cloned', 0)->orderByDesc('created_at')->first();
//            if (!is_null($clone)){
//                return $this->renderJson(['clone_id'=>$clone->id], -1, '你有未使用的克隆,是否使用?');
//            }
//        }
        if (empty(\request('temp_id'))){
            return $this->fail('模板不能为空');
        }
        $temp = UserTemplate::find(\request('temp_id'));
        if (is_null($temp)){
            return $this->fail('模板不存在');
        }
        if ($temp->is_clone != 1){
            return $this->fail('该模板不允许克隆');
        }
        if ($temp->user_id == Auth::id()) {
            return $this->fail('不能克隆自己');
        }
        $id = DB::table('personal_page_template_clone')->insertGetId(['user_id'=>Auth::id(), 'template_id'=>$temp->id, 'amount' => $temp->clone_price, 'created_at'=>Carbon::now()]);
        return $this->renderJson(['clone_id' => $id]);
    }

    /**
     * @SWG\Post(
     *     path="/front/personal_page/custom/pay",
     *     tags={"个人网页"},
     *     summary="克隆余额支付",
     *     description="克隆余额支付",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="clone_id", in="formData", type="string", description="克隆订单id"),
     *     @SWG\Parameter(name="pay_pwd", in="formData", type="string", description="支付密码"),
     *     @SWG\Response(
     *          response="200",
     *          description="成功",
     *      )
     * )
     */
    public function pay(Request $request)
    {
        $this->validate($request, ['clone_id'=>'required', 'pay_pwd'=>'required']);
        $clone = UserTemplateClone::find($request->input('clone_id'));
        if (is_null($clone)){
            return $this->fail('克隆模板错误', 200);
        }
        if ($clone->is_paid == 1){
            return $this->fail('你已经支付过了', 200);
        }

        $re = UserTemplate::find($clone->template_id);
        if (is_null($re)){
            return $this->fail('模板不存在', 200);
        }
        if ($re->clone_price <= 0){
            return $this->fail('该模板不需要支付', 200);
        }
        //校验支付密码
        $pay_pwd = $request->input('pay_pwd');
        if (strlen($pay_pwd) != 6) {
            return $this->fail('支付密码错误', 200);
        }
        if (empty(Auth::user()->payment_password)){
            return $this->fail('你还未设置支付密码，请先设置', 200);
        }
        if (!password_verify($pay_pwd, Auth::user()->payment_password)) {
            return $this->fail('支付密码错误', 200);
        }
        try {
            DB::beginTransaction();
            $user = User::where('id', Auth::id())->lockForUpdate()->first();
            $to = User::where('id', $re->user_id)->lockForUpdate()->first();
            if ($user->money < $re->clone_price) {
                DB::rollBack();
                return $this->fail('余额不足', 200);
            }
            //扣款
            $user->decrement('money', $re->clone_price);
            //日志
            UserBill::create([
                'user_id' => $user->id,
                'income_type' => 0,
                'describe' => "克隆《{$re->title}》",
                'money' => $re->clone_price,
                'type' => 6
            ]);
            //入款
            $to->increment('custom_income', $re->clone_price);
            $to->increment('money', $re->clone_price);
            UserBill::create([
                'user_id' => $to->id,
                'type' => 2,
                'income_type' => 1,
                'describe' => "《{$re->title}》 被克隆",
                'money' => $re->clone_price
            ]);
            //日志
            DB::table('personal_page_custom_clone_bill')->insert([
                'user_id' => $to->id,
                'type' => 1,
                'title' => "《{$re->title}》 被克隆",
                'amount' => $re->clone_price,
                'created_at' => Carbon::now()
            ]);
            $clone->is_paid = 1;
            $clone->save();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('购买失败!请稍后重试');
        }
        return $this->success();
    }

    /**
     * @SWG\Get(
     *     path="/front/personal_page/byuserid",
     *     tags={"个人网页"},
     *     summary="根据用户id获取个人网页列表",
     *     description="根据用户id获取个人网页列表",
     *     produces={"application/json"},
     *     @SWG\Parameter(
     *         name="user_id",
     *         in="query",
     *         description="用户id",
     *         type="integer"
     *     ),
     *     @SWG\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码",
     *         type="integer"
     *     ),
     *     @SWG\Parameter(
     *         name="limit",
     *         in="query",
     *         description="步长",
     *         type="integer"
     *     ),
     *     @SWG\Response(
     *         response="200",
     *         description="个人网页列表",
     *         @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                   @SWG\Property(
     *                        property="id",
     *                        type="integer",
     *                        description="个人网页id"
     *                   ),
     *                   @SWG\Property(
     *                        property="title",
     *                        type="string",
     *                        description="标题"
     *                   ),
     *                   @SWG\Property(
     *                        property="popularity",
     *                        type="integer",
     *                        description="浏览量"
     *                   ),
     *                   @SWG\Property(
     *                        property="clone_price",
     *                        type="integer",
     *                        description="价格"
     *                   ),
     *                   @SWG\Property(
     *                         property="content",
     *                         type="string",
     *                         description="内容"
     *                   )
     *              )
     *          )
     *     )
     * )
     */
    public function getListByUserId()
    {
        $user_id = request('user_id');
        $page = UserTemplate::select(['id','title','popularity','clone_price','content'])->where('user_id', $user_id)->where('type',2)->paginate(request('limit', 10));
        $items = $page->items();
        foreach ($items as &$item) {
            $item->cover = '';
            $content = json_decode($item->content);
            foreach ($content as $value) {
                if ($value->type == 'slider') {
                    $item->cover = $value->children[0]->img->src;
                }
            }
        }
        $page = $page->toArray();
        $page['data'] = $items;
        return $this->renderJson($page);
    }
}
